import { useCartStore } from '@/stores/cart'
import { useRouter } from 'vue-router'
import { useOrderStore } from '@/stores/order'
import { ref, type Ref, onMounted } from "vue"
import type { IGoods,IOrderGoods } from '@/types/type'
import { Toast } from 'vant';

export const useCart = () => {
    const cartStore = useCartStore()
    const orderStore = useOrderStore()
    const router = useRouter()

    const bindBack = () => router.replace({ path: '/' })

    const bindDelete = (id: number) => {
        cartStore.deleteGoods(id)
    }
    const onSubmit =()=>{
        Toast.success('支付成功');
        router.replace({ path: '/' })
    };
    const bindDeleteOrder = (id: number) => {
        orderStore.deleteGoods(id)
    }
    const bindDeleteAll = () => {
        cartStore.deleteAllGoods()
    }
    // 生成订单
    const goods:Ref<IGoods> = ref({
        id: 0,
        shop: '',
        picture: '',
        product: '',
        price: 0,
        oldprice: 0,
        putaway: 0,
        detail: '',
        categoryname: '',
    })
    const bindOrder = () => {
        router.replace({path:'/order'})
        const orderGoods:IOrderGoods={
            id: goods.value.id,//添加商品时的id
            name: goods.value.product,
            price: goods.value.price,
            url: goods.value.picture,
            num: 1,//加入购物车，默认数量是1
            state: false,
            product: goods.value.product,
            oldprice: goods.value.oldprice,
            picture: goods.value.picture
        }
        const olderlist =   cartStore.list.map((item)=>{
            if(item.state== true){
                return {olderState:item.state,num:item.num,name:item.name,id:item.id,url:item.url,price:item.price}
            }
        })
        console.log("goods",goods)
        console.log(orderGoods);
    }
     // 返回购物车
    const backCart=()=>router.replace({path:'/cart'})
    return { cartStore,orderStore, bindDelete, bindOrder, bindBack, bindDeleteAll,backCart,bindDeleteOrder,onSubmit }
}